import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { useDispatch } from 'react-redux'
import type { RootState } from './index'

interface CounterState {
    value: number
    colectList: {
        id?: string
    }[]
    aa: {}[]
}
// 使用该类型定义初始 state
const initialState: CounterState = {
    value: 1,
    colectList: localStorage.getItem('colectlist') ? JSON.parse(localStorage.getItem('colectlist') as string).colectList : [],

    aa: [{}]
}
export const colect = createSlice({


    name: 'example',
    initialState,
    reducers: {

        saveColect: (state, val: PayloadAction<{ id: string }>) => {

            state.colectList.push(val.payload)
            localStorage.setItem('colectlist', JSON.stringify({
                type: 1,
                colectList: state.colectList
            }))
        },
        deletColect: (state, val: PayloadAction<{ id: string }>) => {
            console.log(val.payload);
            state.aa = state.colectList.filter((item) => item.id !== val.payload.id)
            state.colectList = state.aa

            state.colectList.length ? localStorage.setItem('colectlist', JSON.stringify(
                {
                    type: 1,
                    colectList: state.aa
                }
            )) : localStorage.removeItem('colectlist')
        }

    }
})




export const { saveColect, deletColect } = colect.actions
export default colect.reducer